/*!
 * node-util
 * Copyright(c) 2019 huangxin <3203317@qq.com>
 * MIT Licensed
 */
'use strict';

const crypto = require('crypto');

const _ = require('underscore');

let _exp = module.exports;

_exp.genApikey = function() {
  let _diff = crypto.createDiffieHellman(256);
  let _key = _diff.generateKeys('base64');
  let _v = _key.toString('utf-8');
  return _v;
};

_exp.genSeckey = function() {
  return this.genApikey();
};

_exp.validate = function(data, seckey) {
  let _sign1 = data.signature;

  if (!_sign1) {
    return;
  }

  delete data.signature;

  let _sign2 = this.genSignature(data, seckey);
  return (_sign1 === _sign2);
};

_exp.genSignature = function(data, seckey) {
  let _arr = _paramsSort(data);

  let _v1 = crypto.createHmac('sha1', seckey);
  let _v2 = _v1.update(_arr.join(''));
  let _v3 = _v2.digest();
  let _sign = _v3.toString('base64');

  return _sign;
};

/**
 * 参数排序
 *
 * @return
 */
const _paramsSort = _exp.paramsSort = obj => {
  let _keys = _.keys(obj);
  let _sortBy = _.sortBy(_keys, key => key);

  let _arr = [];

  for (let _key of _sortBy) {
    _arr.push(_key);
    _arr.push('=');
    _arr.push(obj[_key]);
  }

  return _arr;
}

/**
 * @param {Object} ts
 */
const _ts = function(ts) {
  ts = ts - 0 || 0;

  let _now = new Date().getTime();

  if ((_now - 1000 * 60 * 3) < ts && ts < (_now + 1000 * 60 * 3)) {
    return true;
  }
};
